package com.stylefeng.guns.modular.system.service.impl;

import com.stylefeng.guns.common.constant.Const;
import com.stylefeng.guns.common.persistence.dao.NetworkTrainMapper;
import com.stylefeng.guns.common.persistence.model.NetworkTrainRule;
import com.stylefeng.guns.common.persistence.service.impl.PointServiceImpl;
import com.stylefeng.guns.modular.system.service.INetworkTrainRuleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.List;

/**
 * <p>
 * 网络培训积分 服务实现类
 * </p>
 *
 * @author jondai
 * @since 2017-12-27
 */
@Service
public class NetworkTrainRuleServiceImpl extends PointServiceImpl<NetworkTrainMapper, NetworkTrainRule> implements INetworkTrainRuleService {

    @Autowired
    private NetworkTrainMapper networkTrainMapper;


    @Override
    public void empty() {
        networkTrainMapper.empty();
    }

    @Override
    public List<NetworkTrainRule> selectAll() {
        return networkTrainMapper.selectAll();
    }

    /**
     * 获取学分上限
     * @return
     */
    @Override
    public Double getUpperLimit() {
        List<NetworkTrainRule> networkTrainRules = this.selectAll();
        return getUpperLimit(networkTrainRules);
    }

    /**
     * 获取学分上限
     * @param networkTrainRules
     * @return
     */
    @Override
    public Double getUpperLimit(List<NetworkTrainRule> networkTrainRules) {
        if(CollectionUtils.isEmpty(networkTrainRules)){
            return Const.NETWORK_UPPERLIMIT;
        }else{
            Double upperLimit = networkTrainRules.get(0).getUpperLimit();
            if(upperLimit == null){
                return Const.NETWORK_UPPERLIMIT;
            }else{
                return upperLimit;
            }
        }
    }

    /**
     * 根据学时计算积分
     * 计算规则：j1积分到j2积分之间是每学时是ss分
     * 方法：1.获取区间规则 2.设置上限值
     * @param hours
     * @return
     */
    @Override
    public Double integralCal(Double hours) {
        Double integral = 0.0;
        Double upper = 999999.0;

        if(hours == null || hours < 0.0){
            integral = 0.0;
        }else{
            List<NetworkTrainRule> networkTrainRules = this.selectAll();

            for (NetworkTrainRule rule : networkTrainRules) {
                if(rule.getStartHours() <= hours && hours <= rule.getEndHours()){
                    integral = hours * rule.getCredit();
                }
                upper = rule.getUpperLimit();
            }
        }

        //设置上限值
        if(integral >= upper){
            integral = upper;
        }

        return integral;
    }

}
